<script setup lang="ts">
import image from "@/assets/pexels-photo-906150.webp";

let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D | null;
const img = new Image();
img.src = image;
img.onload = () => {
  canvas = document.getElementById("imgCanvas") as HTMLCanvasElement;
  ctx = canvas.getContext("2d");
  ctx?.drawImage(img, 0, 0, 800, 531);
};

// 未优化
const imgHandler = () => {
  // 读取所有像素点
  const imageData = ctx?.getImageData(0, 0, 800, 531);
  console.log(imageData);
  const data = imageData?.data;
  // 循环每个像素点，一次给它做计算，这张图42多万像素点，每个像素点的rgba值4个，就是data160多w的数据
  // 循环160w次
  if (imageData) {
    for (let i = 0; i < imageData.data.length; i++) {
      for (let j = 0; j < 1000; j++) {
        if (imageData.data[i] !== 255) {
          if (data) {
            imageData.data[i] = Math.min(data[i] + j, 0);
          }
        }
      }
    }
    ctx?.putImageData(imageData, 0, 0);
  }
};

// 优化
const picWorker = new Worker("http://localhost:5173/picworker.js");
picWorker.addEventListener("message", (e) => {
  const imageData = e.data;
  ctx?.putImageData(imageData, 0, 0);
});
const imgHandlerTurbo = () => {
  // 读取所有像素点
  const imageData = ctx?.getImageData(0, 0, 800, 531);
  console.log(imageData);
  picWorker.postMessage(imageData);
};
</script>

<template>
  <div>
    <h1>Example1——图像处理</h1>
    <section>
      <div>
        <input type="text" />
        <button @click="imgHandler">过滤</button>
        <button @click="imgHandlerTurbo">过滤-优化</button>
      </div>
      <canvas id="imgCanvas" width="800" height="531"></canvas>
    </section>
  </div>
</template>

<style lang="scss" scoped></style>
